from wxauto import WeChat
import time
from chat_handler import ChatHandler

def main():
    # 初始化微信实例
    wx = WeChat()
    
    # 确保微信已登录并选中聊天窗口
    sessions = wx.GetSessionList()
    if not sessions:
        print("请先登录微信")
        return
        
    print("请选择一个聊天窗口...")
    
    # 创建消息处理器
    chat_handler = ChatHandler()
    
    # 记录最后处理的用户消息
    last_user_msg = None
    
    while True:
        try:
            # 获取当前聊天窗口的所有消息
            messages = wx.GetAllMessage()
            if not messages:
                time.sleep(1)
                continue
            
            # 从后往前遍历消息，找到最后一条用户消息
            user_msg = None
            for msg in reversed(messages):
                msg_str = str(msg)
                # 如果不是AI的回复，就是用户消息
                if not msg_str.startswith("AI："):
                    user_msg = msg_str
                    break
            
            # 如果找到了用户消息，且是新消息
            if user_msg and user_msg != last_user_msg:
                print(f"收到用户新消息: {user_msg}")
                
                # 调用AI处理消息
                response = chat_handler.handle_message("text", user_msg, "user")
                
                # 发送回复
                if response:
                    wx.SendMsg(f"AI：{response}")
                    last_user_msg = user_msg
                    print(f"已回复: {response}")
            
            time.sleep(1)
            
        except Exception as e:
            print(f"发生错误: {str(e)}")
            time.sleep(5)

if __name__ == "__main__":
    main() 